#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Software: PyCharm
# @Version : Python-
# @Author  : Shengji He
# @Email   : hsjbit@163.com
# @File    : InsertDeleteGetRandom.py
# @Time    : 2020/10/31 14:45
# @Description:
from collections import defaultdict
import random


class RandomizedCollection:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.d = defaultdict(set)
        self.v = []

    def insert(self, val: int) -> bool:
        """
        Inserts a value to the collection. Returns true if the collection did not already contain the specified element.
        """
        self.d[val].add(len(self.v))
        self.v.append(val)
        return len(self.d[val]) == 1

    def remove(self, val: int) -> bool:
        """
        Removes a value from the collection. Returns true if the collection contained the specified element.
        """
        if not self.d[val]:
            return False
        # self.v[(i := self.d[val].pop())] = self.v[-1]
        # self.d[(last := self.v.pop())].discard(len(self.v))
        i = self.d[val].pop()
        self.v[i] = self.v[-1]
        last = self.v.pop()
        self.d[last].discard(len(self.v))
        i < len(self.v) and self.d[last].add(i)
        return True

    def getRandom(self) -> int:
        """
        Get a random element from the collection.
        """
        return random.choice(self.v)



# Your RandomizedCollection object will be instantiated and called as such:
# obj = RandomizedCollection()
# param_1 = obj.insert(val)
# param_2 = obj.remove(val)
# param_3 = obj.getRandom()


if __name__ == '__main__':
    obj = RandomizedCollection()
    param_1 = obj.insert(1)
    param_2 = obj.remove(1)
    param_3 = obj.insert(1)
    # param_3 = obj.getRandom()
    print('done')
